package com.example.book.config.messageconverter;

import com.alibaba.fastjson.JSON;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.support.TaskExecutorAdapter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Configuration
public class MyWebConfig implements WebMvcConfigurer{
    //使用WebMvcConfigurer中的default方法, 不需要再extends WebMvcConfigurerAdapter


    private static AtomicInteger atomicInteger = new AtomicInteger(0);

    public static ExecutorService executorService = new ThreadPoolExecutor(50, 50, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1000), new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("async-work-Q-" + atomicInteger.getAndAdd(1));
            return thread;
        }
    });


    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {


        for (HttpMessageConverter<?> converter : converters) {

//            ObjectMapper jsonMapper = new ObjectMapper();

            List<MediaType> supportedMediaTypes = converter.getSupportedMediaTypes();
            List<String> collect = supportedMediaTypes.stream().map(e -> e.getType() + "/" + e.getSubtype()).collect(Collectors.toList());

            System.out.println(converter.getClass() + ":::" + JSON.toJSONString(collect));


        }
    }

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        AsyncTaskExecutor taskexecutor = new TaskExecutorAdapter(executorService);
//        ThreadPoolTaskExecutor taskexecutor = new ThreadPoolTaskExecutor();
//        taskexecutor.setThreadNamePrefix("XXXX-");
//        taskexecutor.setMaxPoolSize(50);
//        taskexecutor.setCorePoolSize(50);
//        taskexecutor.setKeepAliveSeconds(3);
//        taskexecutor.setQueueCapacity(1000);
//        taskexecutor.setDaemon(true);
//        taskexecutor.initialize();
        configurer.setTaskExecutor(taskexecutor);
    }
}
